﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.Web;
using RestEntities;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using System.IO;

namespace WpfAppWcfRestConsumer
{
	/// <summary>
	/// Interaction logic for WindowJsonResponse.xaml
	/// </summary>
	public partial class WindowJsonResponse : Window
	{
		public WindowJsonResponse()
		{
			InitializeComponent();
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			WebClient cnt = new WebClient();
			cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);
			cnt.DownloadStringAsync(new Uri("http://localhost:2222/RestService/json/Persons"));
		}

		void cnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			string str = e.Result;
			List<Person> persons = JsonConvert.DeserializeObject<List<Person>>(str);
			lstPersons.ItemsSource = persons;
		}

		private void btnAdd_Click(object sender, RoutedEventArgs e)
		{
			Person person = new Person()
			{
				Comments = new List<Comment>(),
				Id = Person.GetNextPersonId(),
				LastName = "JSON",
				Name = "JSON"
			};
			DataContractJsonSerializer jsondata = new DataContractJsonSerializer(typeof(Person));
			MemoryStream mem = new MemoryStream();
			jsondata.WriteObject(mem, person);
			string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);

			WebClient cnt = new WebClient();
			cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
			cnt.Headers["Content-type"] = "application/json";
			cnt.Encoding = Encoding.UTF8;
			cnt.UploadStringAsync(new Uri("http://localhost:2222/RestService/json/Admin/Person"), "POST", josnserdata);
		}

		private void btnView_Click(object sender, RoutedEventArgs e)
		{
			WebClient cnt = new WebClient();
			cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);
			cnt.DownloadStringAsync(new Uri("http://localhost:2222/RestService/json/Persons"));
		}

		void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
		{
			var x = e; 
		}

		private void lstPersons_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{

		}

		private void miDeletePerson_Click(object sender, RoutedEventArgs e)
		{

		}
	}
}
